var app=getApp();
var ux = require('../../../../lib/ux.js');
Page({

  /**
   * 页面的初始数据
   */
  data: {    
    parma:{},
    userId:null,
    obj:{},
    setting:{},
    banrdName:"",
    banrdId:null,
    banrdimg:"",
    getSessionKeyUrl: "/api/member/getSessionKey.do",
    yjyqUrl: "/api/memberCoupon/getYjyqCouponData.do",
    getUrl: "/api/member/authPhones.do",
    banrdNameUrl:"/api/banrd/getBanrdName.do",
    phoneModle:false,
    authModle:false,
    userInfo:{},
    ok:false,
	action:"",
	submit:"{{submit}}"
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    var self = this;
    var scene = decodeURIComponent(options.scene)
    if (scene && scene != undefined && scene != "undefined") {
      console.log("有参数" + scene)
      var scenes = scene.split("_");
      console.log("scenes[1]" + scenes[1])
      this.setData({
        banrdId: scenes[1],
        userId: scenes[0]
      })
    } else {
      this.setData({
        banrdId: options.banrdId,
        userId: options.userId
      })
    }

    if (this.data.banrdId) {
      wx.setStorageSync("banrdId", this.data.banrdId)
      var pamsas = { banrdId: this.data.banrdId };
      console.log("pamsas" + JSON.stringify(pamsas))
      ux.request(this.data.banrdNameUrl, pamsas, function (protocol) {

        self.setData({
          banrdName: protocol.data.banrdName
        })
      }, true);
    }
    wx.setNavigationBarTitle({
      title: "优惠券领取",
    })
    
    var pams = { banrdId: this.data.banrdId };
    ux.request(this.data.yjyqUrl, pams, function (protocol) {

      self.setData({
        parma:protocol.data.parma,
        obj: protocol.data.obj
      })
    }, true);
    wx.showLoading({
      title: '加载中.....',
      mask: true
    })

    var parmas = {
      merchant: this.data.banrdId,
      memberId: this.data.userId
    }
    self.getShar();
    ux.redLogin(parmas, function (protocol) {
      if (protocol.data.type == 1) {//已授权
        var userInfo = wx.getStorageSync("userInfo");
        var setting = wx.getStorageSync("setting");
        if (userInfo.mobile) {
          wx.hideLoading();
          self.setData({
            setting: setting,
            ok: true,
            userInfo: userInfo,
            msg2: "",
            msg: "您不符合领取的要求"
          })
        } else {
          wx.hideLoading();
          self.getSessionKey();
          self.setData({
            phoneModle: true,
          })
        }
      } else if (protocol.data.type == 2) {//未授权
        wx.hideLoading();
        self.setData({
          authModle: true,
        })
      }
    })
  },
  getShar:function(){
    var self=this;
    var banrdid=this.data.banrdId;
    ux.request("/api/Merchant/getShars.do", {banrd:parseInt(banrdid),type:5},function(data){
      if(data.data.obj){
        self.setData({
          fenxiang:data.data.obj
        })
      }
    });
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },
  goToBAND:function(){
    wx.reLaunch({
      url: '/pages/member/tab1/sugarSpice?id=' + this.data.banrdId,
    })
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {

  },
  getUserInfoFun: function (e) {
    var self = this;
    var userInfo = e.detail.userInfo
    var params = {};
    params.nickname = userInfo.nickName;
    params.header = userInfo.avatarUrl;
    params.sex = userInfo.gender;
    console.log(JSON.stringify(userInfo));
    wx.showLoading({
      mask: true,
      title: '处理中....',
    })
    wx.login({
      success: function (res) {
        if (res.code) {
          params.jscode = res.code;
          ux.request("/api/member/registerUser.do", params,
            function (protocol) {
              if (protocol.success) {
                wx.setStorageSync("userInfo", protocol.data.userInfo);
                wx.setStorageSync("token", protocol.data.token);
                wx.setStorageSync("setting", protocol.data.setting);
                wx.hideLoading();
                self.getSessionKey();
                self.setData({
                  setting: protocol.data.setting,
                  phoneModle:true,
                  authModle: false,
                })
              } else {
                wx.hideLoading();
                wx.showToast({
                  title: '系统繁忙!',
                })
              }
            }, true);
        } else {
          console.log('登录失败！' + res.errMsg)
        }
      },
      complete: function (res) {
        console.log(JSON.stringify(res))
      }
    })
  },

  getSessionKey() {
    var self = this;
    wx.login({
      success: function (res) {
        if (res.code) {
          var parmas = { jscode: res.code }
          ux.request(self.data.getSessionKeyUrl, parmas, function (data) {
            self.setData({
              openid: data.data.openid,
              session_key: data.data.session_key
            })
          });
        } else {
          console.log('登录失败！' + res.errMsg)
        }
      },
      complete: function (res) {
        console.log(JSON.stringify(res))
      }
    })
  },
  getPhoneNumbers: function (e) {
    var self = this;
    var vi = e.detail.iv;
    var encData = e.detail.encryptedData;
    if (!vi) {
      wx.showToast({
        title: '请授权手机号码',
      })
      return false;
    }
    wx.showLoading({
      mask: true,
      title: '处理中....',
    })

    var params = { banrdId: self.data.banrdId, otherId: self.data.memberId, session_key: self.data.session_key, openid: self.data.openid,  vi: vi, encData: encData };
    ux.request(self.data.getUrl, params, function (data) {
      wx.hideLoading();
      wx.setStorageSync("userInfo", data.data.userInfo);
      wx.setStorageSync("token", data.data.token);
      wx.setStorageSync("setting", data.data.setting);
      self.toast("授权成功");
      self.setData({
        msg2: "已放入 "+self.data.banrdName+" 您的'" + data.data.userInfo.mobile + "'帐户",
        msg: "恭喜您成功领取",
        setting:data.data.setting,
        phoneModle: false,
        userInfo: data.data.userInfo,
        ok:true,
      })
    }, true);
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  
  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    var that = this;
    wx.showShareMenu({
      withShareTicket: true
    })
    var userInfo = this.data.userInfo;
    var obj = this.data.setting;
    console.log(obj.wechatTitle);
    var shareObj = {
      title: this.data.fenxiang.shareTitle,
      path: '/pages/member/tab3/coupon/couponGet?banrdName=' + that.data.banrdName + '&userId=' + this.data.userId + "&banrdId=" + this.data.banrdId,
      imageUrl: this.data.fenxiang.url,
      success: function (res) {
        // 转发成功之后的回调
        if (res.errMsg == 'shareAppMessage:ok') {
          that.toast("转发成功");
        }
      },
      fail: function () {
        // 转发失败之后的回调
        if (res.errMsg == 'shareAppMessage:fail cancel') {
          that.toast("取消转发");
        } else if (res.errMsg == 'shareAppMessage:fail') {
          that.toast("转发失败");
        }

      }
    }
    return shareObj;
  },
  toast: function (params) {
    if (typeof (params) == "string") {
      params = { content: params };
    }
    this.setData({
      toast: params.content
    });
    var THIS = this;
    setTimeout(function () {
      THIS.setData({
        toast: false
      });
      if (params.complete) {
        params.complete();
      }
    }, params.time || 3000);
  }
})
